package org.epidroid.epidroid.androsoul.ui.contactlist;

import org.epidroid.epidroid.R;
import org.epidroid.epidroid.androsoul.engine.communication.Connection;
import org.epidroid.epidroid.androsoul.engine.service.IAndroSoulService;
import org.epidroid.epidroid.androsoul.ui.AndroSoulActivity;
import org.epidroid.epidroid.androsoul.ui.utils.TextFormater;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

public class HeaderView {

	IAndroSoulService _service = null;
	AndroSoulActivity _context = null;
	LinearLayout _layout = null;
	TextView _txtViewLogin = null;
	TextView _txtViewState = null;
	TextView _txtViewLocation = null;

	public HeaderView(IAndroSoulService service, AndroSoulActivity context) {
		_service = service;
		_context = context;
		_layout = (LinearLayout) _context.findViewById(R.id.androsoul_header);
		_txtViewLogin = (TextView) _context.findViewById(R.id.header_login);
		_txtViewState = (TextView) _context.findViewById(R.id.header_state);
		_txtViewLocation = (TextView) _context
				.findViewById(R.id.header_location);

		_txtViewState.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				showStateDialog();
			}
		});
	}

	/**
	 * Update content of the header (login + state)
	 */
	public void update() {
		if (_service.getMySelf() == null) {
			// User not configured
			_txtViewLogin.setText(R.string.androsoul);
			_txtViewState.setText("");
			_txtViewLocation.setText("");
			return;
		}

		String login = _service.getMySelf().getName();
		String state = _service.getMySelf().getState();
		String location = TextFormater.reduceString(_service.getMyLocation(),
				35);
		if (_service.getConnectionState() != Connection.State.AUTHENTIFIED)
			state = "Offline";
		_txtViewLogin.setText(login);
		_txtViewState.setText("(" + state + ")");
		_txtViewLocation.setText(location);
	}

	private void showStateDialog() {

		if (_service.getConnectionState() != Connection.State.AUTHENTIFIED)
			return;

		AlertDialog.Builder alert = new AlertDialog.Builder(_context);
		alert.setTitle(R.string.state_change);

		alert.setItems(R.array.states_array, new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				String state = _context.getResources().getStringArray(
						R.array.states_array)[which];
				_service.setMyState(state);
				update();
			}
		});

		alert.setNeutralButton(R.string.logout, new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				_context.switchLogin();
			}
		});

		alert.setNegativeButton(R.string.cancel, null);
		alert.show();
	}
}
